#include <taskManager.h>

uint16_t taskFlags = 0;
uint16_t tasksMask = 0xFFFF;
uint8_t tasktimes = 0;
static void (*taskHandlers[])() = {
    [TASK_ID_SOFT_TIMER]        = SoftTimer_TaskHandler,
    [TASK_ID_LINS]              = LINS_TaskHandler,
#if LIN_MASTER_EN == 1
    [TASK_ID_LINM]              = LINM_TaskHandler,
#endif
    [TASK_ID_ADC]               = ADC_TaskHandler,
    [TASK_ID_COLOR_MIXING]      = CLM_TaskHandler,
    [TASK_ID_APPL]              = APPL_TaskHandler,
};

void IdleTask(void)
{
  
  
}

void TM_RunTasks(void)
{
    uint8_t taskId;
    tasktimes++;
    for (taskId = 0; taskId < (sizeof(taskHandlers) / sizeof(taskHandlers[0])); taskId++){
     if ( ((uint16_t)1u << taskId) & (taskFlags & tasksMask) ){
           __atomic_enter();
                taskFlags &= ~((uint16_t)1u << taskId);
            __atomic_exit();
            if (taskHandlers[taskId]){
                taskHandlers[taskId]();
            }
            break;
        }
    }
    
    if (taskFlags == 0u){
        IdleTask();
    }
}


/***************************************************************************//**
\brief Disables specified task.

\param[in] taskId - task to be disabled.
*******************************************************************************/
void TM_DisableTask(TM_TaskId_t taskId)
{
    tasksMask &= ~(1u << taskId);
}

/***************************************************************************//**
\brief Enables specified task.

\param[in] taskId - task to be enabled.
*******************************************************************************/
void TM_EnableTask(TM_TaskId_t taskId)
{
    tasksMask |= (1u << taskId);
}
/***************************************************************************//**
\brief runs specified task.

\param[in] taskId - task to be run.
*******************************************************************************/
void TM_PostTask(TM_TaskId_t taskId)
{
    __atomic_enter();
      taskFlags |= ( (uint16_t)1 << taskId);
    __atomic_exit();
}

